<template>
	<view class="root-container">
		<view v-if="isLoaded" :class="hasComment ? 'item-container' :'item-margin-container'">
			<text class="item-title">{{blog.title}}</text>
			<text class="item-author">{{blog.user.nickName}}@{{blog.createTime}}</text>
			<rich-text :nodes="blog.content" class="item-content"></rich-text>
			<image :src="blog.picture" mode="widthFix" class="img item-picture"></image>
			<view>
				<view v-for="(tag,idx) in blog.tags" :key="idx" class="item-tag">{{tag}}</view>
			</view>
			<image :src="blog.user.avatar" mode="aspectFill" class="item-avatar"></image>
			<view class="icon-container">
				<image v-if="hasGood" src="../../static/icons/ic_good_fill.png" class="icon"
					@click.stop="changeGood(blog.id,false)"></image>
				<image v-else src="../../static/icons/ic_good.png" class="icon" @click.stop="changeGood(blog.id,true)">
				</image>
				<text class="icon-text">{{blog.good}}</text>
				<image src="../../static/icons/ic_comment.png" class="icon"></image>
				<text class="icon-text">{{blog.comments.length}}</text>
				<image src="../../static/icons/ic_count.png" class="icon"></image>
				<text class="icon-text">{{blog.readCount}}</text>
			</view>
		</view>
		<view v-if="hasComment" class="comments-container">
			<view v-for="(item,index) in parents" :key="item.id">
				<view class="cmt-container">
					<text class="cmt-author">{{item.nickName}}</text>
					<text class="cmt-time">{{item.createTime}}</text>
					<text class="cmt-content" @click="clickToReply(item)">{{item.content}}</text>
					<image :src="item.avatar" mode="aspectFill" class="cmt-avatar"></image>
				</view>
				<view v-if="replies[index].length > 0" class="replies-container">
					<view class="reply-item" v-for="(reply,idx) in replies[index]" :key="reply.id">
						<view class="reply-info">
							<text class="reply-author">{{reply.nickName}}:</text>
							<text class="reply-to">{{reply.toUser}}</text>
							<text class="reply-time">{{reply.createTime}}</text>
						</view>
						<text class="reply-content" @click="clickToReply(reply)">{{reply.content}}</text>
					</view>
				</view>
				<view v-if="index < parents.length - 1" class="cmt-line"></view>
			</view>
		</view>
		<view class="input-container">
			<image :src="avatar" mode="aspectFill" class="input-avatar" @click="clickToLogin"></image>

			<textarea v-model="inputValue" :placeholder="inputHolder" placeholder-class="input-holder" auto-height
				class="input-area" @input="inputGetComment" />
			<text class="iconfont icon-commit input-commit" @click="clickCommit"></text>
		</view>
		<login-dialog ref="login" @after="afterLogin"></login-dialog>
	</view>
</template>

<script>
	let parentId = null
	let cmtValue = ""
	let app = getApp()
	export default {
		data() {
			return {
				blog: {},
				hasGood: false,
				isLoaded: false,
				hasComment: false,
				parents: [], //{},{},根评论集合
				replies: [], //
				avatar: '../../static/icons/default_user.png',
				inputHolder: "请输入评论内容",
				inputValue: "",
				good_ids: []

			}
		},
		onLoad(options) {

			let id = options.id
			let good_ids = uni.getStorageSync(this.$params.key_good_ids)
			if (good_ids) {
				this.hasGood = good_ids.indexOf(id) >= 0
			}
			this.addReadCount(id)
			let prefix = app.globalData.token.length == 0 ? '' : this.$params.host
			this.avatar = prefix + app.globalData.avatar
			this.$noti.add(this.$params.noti_login_status, this, this.afterLogin)
		},
		onUnload() {
			this.$noti.remove(this.$params.noti_login_status, this) //this.afterLogin
		},
		methods: {
			//刷新评论数
			refreshComment(cmt) {
				this.blogs.forEach(b => {
					if (b.id == cmt.blogId) {
						b.comments.push(cmt)
					}
				})
			},
			clickCommit() {
							if (app.globalData.token.length == 0) {
								this.$refs.shell.show()
								return
							}
							if (cmtValue.trim().length == 0) {
								uni.showToast({
									title: '请输入评论内容',
									icon: 'none'
								});
								return
							}
							let url = this.$params.host + this.$params.action_add_comment
							let data = {
								blog_id: this.blog.id,
								token: app.globalData.token,
								parent_id: parentId,
								nick_name: app.globalData.nickName,
								email: app.globalData.email,
								is_owner: app.globalData.uid == this.blog.user.id,
								content: cmtValue,
								avatar: "/" + app.globalData.avatar
							}
							this.$request.post(url, data, res => {
								console.log(res);
								let cmt = res.data
								this.blog.comments.push(cmt)
								this.formatComments(this.blog.comments)
								this.hasComment = this.blog.comments.length > 0
								this.inputHolder = "请输入评论..."
								this.inputValue = ""
								//用页面站方式更新评论数据
								let pages= getCurrentPages()
								let prev = pages[pages.length-2]
								prev.refreshComment(cmt)
								cmtValue = ""
								parentId = null
								// this.componentsByValue(this.blog)
							})
						},
			clickToLogin() {
				this.$refs.login.show()
			},
			afterLogin() {
				this.avatar = this.$params.host + app.globalData.avatar
			},
			inputGetComment(e) {
				cmtValue = e.detail.value
			},
			clickToReply(item) {
				parentId = item.id
				this.inputHolder = "@" + item.nickName
			},
			//评论数+1
			addReadCount(id) {
				let url = this.$params.host + this.$params.action_add_count
				let data = {
					id: id
				}
				this.$request.postParams(url, data, res => {
					let count = res.data.data

					let args = {
						id: id,
						count: count
					}
					this.$noti.post(this.$params.noti_blog_count, args)
					this.getBlog(id)
				})
			},
			//获取详情页
			getBlog(id) {
				let url = this.$params.host + this.$params.action_blog + id
				this.$request.get(url, res => {
					this.blog = res.data.data
					uni.setNavigationBarTitle({
						title: this.blog.user.nickName
					})
					if (!this.blog.picture.startsWith('http')) {
						this.blog.picture = this.$params.host + this.blog.picture
					}
					if (!this.blog.user.avatar.startsWith('http')) {
						this.blog.user.avatar = this.$params.host + this.blog.user.avatar
					}
					this.blog.content = this.blog.content.replace(/\<img/gi, '<img class="rich-img" ')
					console.log(this.blog.createTime);
					this.blog.createTime = this.$utils.formatTime(new Date(this.blog.createTime))
					this.blog.updateTime = this.$utils.formatTime(new Date(this.blog.updateTime))
					this.isLoaded = true
					this.hasComment = this.blog.comments.length > 0
					this.formatComments(this.blog.comments)
				})
			},
			//评论
			formatComments(comments) {
				if (comments.length == 0) {
					return
				}
				this.parents = []
				comments.forEach(item => {
					if (!item.avatar.startsWith('http')) {
						item.avatar = this.$params.host + item.avatar
					}
					item.createTime = this.$utils.formatTime(new Date(item.createTime))
					if (item.parentId == null) {
						this.parents.push(item)
					}
				})
				this.parents.sort(function(c1, c2) {
					return new Date(c2.createTime) - new Date(c1.createTime)
				})
				this.replies = new Array(this.parents.length).fill([])
				let index = 0
				this.parents.forEach(root => {
					let children = []
					children = children.concat(this.getAllChildren(root, comments))
					this.replies[index++] = children
					//过滤掉已经确定是某根评论的子孙评论
					comments = comments.filter(c => children.every(cc => cc.id != c.id))
				})
			},
			getAllChildren(root, comments) {
				let results = []
				comments.forEach(c => {
					if (c.parentId == root.id) {
						c.toUser = root.nickName
						results = results.concat(c)
						let cmts = comments.filter(cmt => cmt.id != c.id)
						let grandson = this.getAllChildren(c, cmts)
						results = results.concat(grandson)
					}
				})
				return results

			},
			//点赞
			changeGood(id, isGood) {
				this.hasGood = isGood
				if (isGood) {
					this.good_ids.push(id)
				} else {
					let index = this.good_ids.indexOf(id)
					if (index > -1) {
						this.good_ids.slice(index, 1)
					}
				}
				uni.setStorageSync(this.$params.key_good_ids, this.good_ids)
				this.switchGood(id, isGood)
			},
			switchGood(id, isGood) {
				let action = isGood ? this.$params.action_good : this.$params.action_del_good
				let url = this.$params.host + action
				let data = {
					"id": id
				}
				this.$request.postParams(url, data, res => {
					this.blog.good = res.data.data
					let good = this.blog.good
					let good_ids = this.good_ids
					this.blog.id = id
					//注册通知
					let args = {
						id: id,
						good: good,
						good_ids: good_ids
					}
					this.$noti.post(this.$params.noti_blog_good, args)
				})
			},
		}
	}
</script>

<style>
	@import url("blog.css");

	.content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}
</style>
